//
//  ZYBImageHelper.m
//  homework
//
//  Created by weiwang on 15/11/23.
//  Copyright © 2015年 zyb. All rights reserved.
//

#import "ZYBImageHelper.h"
#import "NSString+Safety.h"

#define SMALL_IMAGE_URL                   @"http://hiphotos.baidu.com/zhidao/abpic/item/"
#define BIG_IMAGE_URL                     @"http://hiphotos.baidu.com/zhidao/pic/item/"
#define ZYB_IMAGE_URL                     @"https://img.zuoyebang.cc"
#define ZYB_IMAGE1_URL                    @"https://img1.zuoyebang.cc"
#define ZYB_IMAGE_URL_TEST                @"https://testimg.zuoyebang.cc"
static CGFloat const kFillThreshold = 0.45;

@implementation ZYBImageHelper

+ (NSString *)zybImageUrlWithPid:(NSString *)pid isBigImage:(BOOL)isBig isWebp:(BOOL)isWebp {
    NSString *url = nil;
    NSString *imageHost = ZYB_IMAGE_URL;
    NSInteger hostNum = 0;
    if ([pid hasPrefix:@"zyb"] && ([pid rangeOfStringSafely:@"_"].location != NSNotFound)) {
        imageHost = [imageHost stringByReplacingOccurrencesOfString:@"https://img" withString:[NSString stringWithFormat:@"https://img%@",[pid substringWithRangeSafely:NSMakeRange(3, [pid rangeOfStringSafely:@"_"].location-3)]]];
        hostNum = [[pid substringWithRangeSafely:NSMakeRange(3, [pid rangeOfStringSafely:@"_"].location-3)] integerValue];
    }
    
    if (isWebp) {
        if (isBig) {
            if (hostNum >= 10 && hostNum <= 19) {
                url = [NSString stringWithFormat:@"%@/%@.jpg?imageView2/format/webp", imageHost, pid];
            }else{
                url = [NSString stringWithFormat:@"%@/%@.jpg@f_webp", imageHost, pid];
            }
        } else {
            if (hostNum >= 10 && hostNum <= 19) {
                url = [NSString stringWithFormat:@"%@/%@.jpg?imageView2/2/w/200/h/200/format/webp", imageHost, pid];
            }else{
                url = [NSString stringWithFormat:@"%@/%@.jpg@s_0,w_200,h_200,f_webp", imageHost, pid];
            }
        }
    } else {
        if (isBig) {
            url = [NSString stringWithFormat:@"%@/%@.jpg", imageHost, pid];
        } else {
            if (hostNum >= 10 && hostNum <= 19) {
                url = [NSString stringWithFormat:@"%@/%@.jpg?imageView2/2/w/200/h/200", imageHost, pid];
            }else{
                url = [NSString stringWithFormat:@"%@/%@.jpg@s_0,w_200,h_200", imageHost, pid];
            }
        }
    }
    return url;
}


+ (NSString *)zybQAImageUrlWithPid:(NSString *)pid isBigImage:(BOOL)isBig isWebp:(BOOL)isWebp {
    NSString *url = nil;
    
    NSString *imageHost = ZYB_IMAGE_URL_TEST;
    
    if (isWebp) {
        if (isBig) {
            url = [NSString stringWithFormat:@"%@/%@.jpg@f_webp", imageHost, pid];
        } else {
            url = [NSString stringWithFormat:@"%@/%@.jpg@s_0,w_200,h_200,f_webp", imageHost, pid];
        }
    } else {
        if (isBig) {
            url = [NSString stringWithFormat:@"%@/%@.jpg", imageHost, pid];
        } else {
            url = [NSString stringWithFormat:@"%@/%@.jpg@s_0,w_200,h_200", imageHost, pid];
        }
    }
    return url;
}

+ (NSString *)baiduPhotosUrlWithPid:(NSString *)pid isBigImage:(BOOL)isBig isWebp:(BOOL)isWebp {
    NSString *url = nil;
    if (isWebp) {
        url = isBig ? [NSString stringWithFormat:@"%@%@.webp", BIG_IMAGE_URL, pid] : [NSString stringWithFormat:@"%@%@.webp", SMALL_IMAGE_URL, pid];
    } else {
        url = isBig ? [NSString stringWithFormat:@"%@%@.jpg", BIG_IMAGE_URL, pid] : [NSString stringWithFormat:@"%@%@.jpg", SMALL_IMAGE_URL, pid];
    }
    return url;
}

+ (NSString *)imageUrlWithPid:(NSString *)pid isBigImage:(BOOL)isBig isWebp:(BOOL)isWebp
{
    if ([pid hasPrefix:@"http:"] || [pid hasPrefix:@"https:"]) {
        return pid;
    }
    if ([pid hasPrefix:@"zyb"]) {
        return [self zybImageUrlWithPid:pid isBigImage:isBig isWebp:isWebp];
    }
    
    if ([pid hasPrefix:@"qa_"]) {
        return [self zybQAImageUrlWithPid:pid isBigImage:isBig isWebp:isWebp];
    }
    
    return [self baiduPhotosUrlWithPid:pid isBigImage:isBig isWebp:isWebp];
}


+ (UIViewContentMode)imageContentModeWithImageSize:(CGSize)imageSize boundSize:(CGSize)boundsSize
{
    UIViewContentMode contentMode = UIViewContentModeScaleAspectFit;
    BOOL isFill = NO;
    
    if ((boundsSize.width > boundsSize.height) && imageSize.width > imageSize.height) {
        double t = ((boundsSize.width / boundsSize.height) - (imageSize.width / imageSize.height));
        if (t > -kFillThreshold && t < kFillThreshold) {
            isFill = YES;
        }
    }else if ((boundsSize.width < boundsSize.height) && imageSize.width < imageSize.height) {
        double t = ((boundsSize.height / boundsSize.width) - (imageSize.height / imageSize.width));
        if (t > -kFillThreshold && t < kFillThreshold) {
            isFill = YES;
        }
    }
    
    if (isFill) {
        contentMode = UIViewContentModeScaleAspectFill;
    }
    return contentMode;
}

+ (NSString *)imageUrlWithPid:(NSString *)pid isBigImage:(BOOL)isBig
{
    return [self imageUrlWithPid:pid isBigImage:isBig isWebp:YES];
}

+ (NSString *)imageUrlWithPicUrl:(NSString *)picUrl {
    
    if ([picUrl rangeOfString:@"img.zuoyebang.cc"].location != NSNotFound) {
        return picUrl;
    }
    
    if ([picUrl rangeOfString:@"charge.zuoyebang.cc"].location != NSNotFound) {
        return picUrl;
    }
    if ([picUrl rangeOfString:@"gz.bcebos.com"].location != NSNotFound) {
        return picUrl;
    }
    if ([picUrl rangeOfString:@"test-charge.bj.bcebos.com"].location != NSNotFound) {
        return picUrl;
    }
    
    if ([picUrl hasSuffix:@".png"] || [picUrl hasSuffix:@".jpg"] || [picUrl hasSuffix:@".jpeg"] || [picUrl hasSuffix:@".gif"] || [picUrl hasSuffix:@".svg"]) {
        return picUrl;
    }
    
    return [NSString stringWithFormat:@"%@.webp",picUrl];
}

@end

#import "UIImageView+WebCache.h"
#import <objc/runtime.h>

static char UIImageViewDisplayNotAnimated;
static char RealContentMode;
static char PlaceholderImageContentMode;


@implementation UIImageView (SDImageSwizzle)

@dynamic displayNotAnimated;
@dynamic realContentMode;
@dynamic placeholderImageContentMode;

- (UIViewContentMode)realContentMode
{
    NSNumber *number = objc_getAssociatedObject(self, &RealContentMode);
    return [number integerValue];
}

- (void)setRealContentMode:(UIViewContentMode)realContentMode
{
    NSNumber *number = [NSNumber numberWithInteger:realContentMode];
    objc_setAssociatedObject(self, &RealContentMode, number, OBJC_ASSOCIATION_ASSIGN);
}

- (UIViewContentMode)placeholderImageContentMode
{
    NSNumber *number = objc_getAssociatedObject(self, &PlaceholderImageContentMode);
    return [number integerValue];
}

- (void)setPlaceholderImageContentMode:(UIViewContentMode)placeholderImageContentMode
{
    NSNumber *number = [NSNumber numberWithInteger:placeholderImageContentMode];
    objc_setAssociatedObject(self, &PlaceholderImageContentMode, number, OBJC_ASSOCIATION_ASSIGN);
}

- (BOOL)displayNotAnimated
{
    NSNumber *number = objc_getAssociatedObject(self, &UIImageViewDisplayNotAnimated);
    return [number boolValue];
}

- (void)setDisplayNotAnimated :(BOOL)_displayNotAnimated
{
    NSNumber *number = [NSNumber numberWithBool:_displayNotAnimated];
    objc_setAssociatedObject(self, &UIImageViewDisplayNotAnimated, number, OBJC_ASSOCIATION_ASSIGN);
}

- (BOOL)hasPid:(NSString *)pid
{
    return pid.length > 0;
}

- (void)setImageWithPid:(NSString *)pid isBigImage:(BOOL)isBig placeholderImage:(UIImage *)placeholderImage
{
    [self setImageWithPid:pid isBigImage:isBig placeholderImage:placeholderImage completed:nil];
}

- (void)setImageWithPid:(NSString *)pid isBigImage:(BOOL)isBig placeholderImage:(UIImage *)placeholderImage cropAtTopLeft:(CGRect)cropRect
{
//    if (CGRectIsNull(cropRect)) {
//        cropRect = self.frame;
//    }
//    if (CGRectEqualToRect(CGRectZero, cropRect)) {
//        cropRect = self.frame;
//    }
    __weak typeof(self) weakSelf = self;
    [self setImageWithPid:pid isBigImage:isBig placeholderImage:placeholderImage completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
        [weakSelf setImage:image];
    }];
}

-(void)setImageWithPid:(NSString *)pid isBigImage:(BOOL)isBig placeholderImage:(UIImage*)placeholderImage completed:(SDWebImageCompletionBlock)block
{
    //test webp url
    //http://demo.btorange.com/article/webp/demo2.webp
    
    __weak typeof(self) weakSelf = self;
    if ([self hasPid:pid]) {
        NSURL *imageURL = [NSURL URLWithString:[ZYBImageHelper imageUrlWithPid:pid isBigImage:isBig]];
        
        if (self.placeholderImageContentMode) {
            self.contentMode = self.placeholderImageContentMode;
        }
        
        [self sd_setImageWithURL:imageURL placeholderImage:placeholderImage completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
            if (cacheType == SDImageCacheTypeNone && !self.displayNotAnimated)
            {
                weakSelf.alpha = 0;
                [UIView animateWithDuration:0.3 animations:^{
                    weakSelf.alpha = 1;
                }];
            }
            if (block) {
                block(image,error,cacheType,imageURL);
            }
            
            if (image && weakSelf.realContentMode) {
                weakSelf.contentMode = weakSelf.realContentMode;
            }
        }];
    }
    else
    {
        self.image = placeholderImage;
        if (self.placeholderImageContentMode) {
            self.contentMode = self.placeholderImageContentMode;
        }
    }
}
- (BOOL)hasPicUrlX:(NSString *)picUrlX {
    return picUrlX.length > 0;
}
/* 下载原图裁剪后的图片 */
-(void)setimageWithPicUrlX:(NSString *)picUrlX placeholderImage:(UIImage*)placeholderImage completed:(SDWebImageCompletionBlock)block{
    
    __weak typeof(self) weakSelf = self;
    if ([self hasPicUrlX:picUrlX]) {
        
        NSURL *imageURL = [NSURL URLWithString:[ZYBImageHelper imageUrlWithPicUrl:picUrlX]];
        
        if (self.placeholderImageContentMode) {
            self.contentMode = self.placeholderImageContentMode;
        }
        
        [self sd_setImageWithURL:imageURL placeholderImage:placeholderImage completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
            
            if (cacheType == SDImageCacheTypeNone && !self.displayNotAnimated) {
                weakSelf.alpha = 0;
                [UIView animateWithDuration:0.3 animations:^{
                    weakSelf.alpha = 1;
                }];
            }
            if (block) {
                block(image,error,cacheType,imageURL);
            }
            if (weakSelf.realContentMode) {
                weakSelf.contentMode = weakSelf.realContentMode;
            }
        }];
        
    }else {
        
        self.image = placeholderImage;
        if (self.placeholderImageContentMode) {
            self.contentMode = self.placeholderImageContentMode;
        }
    }
    
}



@end
